﻿#include "TcpCodec.h"

#include "TcpIOer.h"
#include "ReadMEMSDataCodec_Client.h"

#include "TcpCodec_HeartBeat.h"
#include "TcpCodec_ReadSensorData.h"
#include "TcpCodec_DataBase.h"
#include "TcpCodec_MCUCtl.h"
#include "TcpCodec_MEMSData.h"
#include "TcpCodec_TurnTable.h"
#include "TcpCodec_Register.h"
#include "TcpCodec_User.h"

#include "MEMSData.h"

TcpCodec::TcpCodec()
{
  setObjectName(getClassNameFirstLow<TcpCodec>());
//  codecMap.insert(TcpCodecBase::HeartBeat,new TcpCodec_HeartBeat());
//  codecMap.insert(TcpCodecBase::ReadSensorData,new TcpCodec_ReadSensorData());
//  codecMap.insert(TcpCodecBase::DataBase,new TcpCodec_DataBase());
//  codecMap.insert(TcpCodecBase::MCUCtl,new TcpCodec_MCUCtl());
//  codecMap.insert(TcpCodecBase::MEMSData,new TcpCodec_MEMSData());
//  codecMap.insert(TcpCodecBase::TurnTable,new TcpCodec_TurnTable());
//  codecMap.insert(TcpCodecBase::Register,new TcpCodec_Register());
//  codecMap.insert(TcpCodecBase::User,new TcpCodec_User());
}

TcpCodec::~TcpCodec()
{
//  for(uchar key:codecMap.keys())
//    {
//      delete codecMap.value(key);
//    }
}

void TcpCodec::code(DataPackage_TcpCodec* dataPackage_TcpCodec)
{
  if(tcpIOer->state()!=TcpIOer::ConnectedState)
    {
      return;
    }
  tcpIOer->sendData(dataPackage_TcpCodec->getData().prepend(dataPackage_TcpCodec->getPackageType()));
}

void TcpCodec::code(uchar type,QByteArray data)
{
  DataPackage_TcpCodec dataPackage_TcpCodec;
  code((&dataPackage_TcpCodec)
       ->setPackageType(type)
       ->setData(data));
}

void TcpCodec::decode(DataPackage_TcpCodec* dataPackageInfo_User)
{
  uchar type=dataPackageInfo_User->getPackageType();
  if(!codecMap.contains(type))
    {
      return;
    }
  codecMap.value(type)->decode(dataPackageInfo_User);
}

void TcpCodec::addToCodecMap(uchar type,TcpCodecBase* tcpCodecBase)
{
  codecMap.insert(type,tcpCodecBase);
}

void TcpCodec::slot_decode(QByteArray data)
{
  if(data.isEmpty())
    {
      return;
    }
  DataPackage_TcpCodec* dataPackageInfo_User
      =(new DataPackage_TcpCodec())
      ->setPackageType(data[0])
      ->setData(data.mid(1));
  decode(dataPackageInfo_User);
  dataPackageInfo_User->deleteLater();
}

TcpIOer* TcpCodec::getTcpIOer()
{
  return tcpIOer;
}

TcpCodec *TcpCodec::setTcpIOer(TcpIOer* tcpIOer)
{
  if(Q_NULLPTR!=this->tcpIOer)
    {
      disconnect(this->tcpIOer,&TcpIOer::signal_dataReceived,this,&TcpCodec::slot_decode);
    }
  this->tcpIOer=tcpIOer;
  if(Q_NULLPTR!=this->tcpIOer)
    {
      connect(this->tcpIOer,&TcpIOer::signal_dataReceived,this,&TcpCodec::slot_decode);
    }
  printInjection(this,tcpIOer);
  return this;
}


void TcpCodec::objectAutoInjection(QHash<QString,QObject*>* objMap)
{
  setTcpIOer(getObjFromMap<TcpIOer>(objMap));
//  for(unsigned char key:codecMap.keys())
//    {
//      ObjAutoInject* temp=dynamic_cast<ObjAutoInject*>(codecMap.value(key));
//      if(temp)
//        {
//          temp->objectAutoInjection(objMap);
//        }
//    }
}



